/* 
 * File:   rfMain.c
 * Author: Ken
 *
 * Created on July 4, 2013, 9:38 PM
 */

// PIC16F883 Configuration Bit Settings

#include "timer.h"
#include "uart.h"

__CONFIG(FOSC_HS & WDTE_OFF & PWRTE_OFF & MCLRE_OFF & CP_OFF & CPD_OFF & BOREN_OFF & IESO_OFF & FCMEN_OFF & LVP_OFF);
__CONFIG(BOR4V_BOR40V & WRT_OFF);

#define LED1    RC0
#define LED2    RC1
#define BUTTON  RB0

#define FRAME_SIZE  10

uint8_t rfData[FRAME_SIZE] = {0};
uint8_t frame_len = 0;
void interruptEnable(bool en);

void interrupt onInterrupt()
{
    static uint8_t bytes = 0;
    static uint8_t count = 0;
    uint8_t data = 0;
    interruptEnable(false);

    if (RBIF)
    {
        //timer1_start();
        bytes |= (0x01 & RB0) << count;
        count++;
        data = PORTB;
        RBIF = 0;
        if (count == 8)
        {
            rfData[frame_len] = bytes;
            frame_len++;
            count = 0;
            bytes = 0;
        }
    }

    //    if (timer1_is_timeout())
    //    {
    //        frame_len++;
    //        rfData[frame_len] = bytes;
    //        count = 0;
    //        bytes = 0;
    //    }
    interruptEnable(true);
}

void interruptEnable(bool en)
{
    IOCB0 = en;
    PEIE = en;
    GIE = en;
    RBIE = en;
    TMR1IE = en;
}

int main()
{
    uint8_t d[3] = {0x31, 0x32, 0x33};
    TRISC0 = 0;
    TRISC1 = 0;
    TRISB0 = 1;
    ANSELH = 0;
    WPUB0 = 1;
    OPTION_REGbits.nRBPU = 0;
    LED1 = 0;
    LED2 = 0;
    interruptEnable(true);
    uart_open(9600);
    timer1_init();
    uart_write_string("\r\nWelcome to RF app demo\r\n");
    while (1)
    {
        //if (timer1_is_timeout())
        if (frame_len == 2)
        {
            //resetTimer();
            interruptEnable(false);
            LED1 = 1;
            uart_write_frame(rfData, frame_len);
            frame_len = 0;
        }
    }
    return 0;
}
